<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-input
        v-model="listQuery.uid"
        clearable
        placeholder="用户ID"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.type" placeholder="类型" clearable style="width: 120px" class="filter-item">
        <el-option v-for="item in typeOptions" :key="item.name" :label="item.name" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.isdel" placeholder="状态" clearable style="width: 120px" class="filter-item">
        <el-option v-for="item in delOptions" :key="item.name" :label="item.name" :value="item.value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      height="550"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传用户" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.user.nickname }}</span>
        </template>
      </el-table-column>

      <el-table-column label="文件" width="350" align="center">
        <template slot-scope="{row}">
          <el-image
            v-if="row.file_type==0"
            :src="row.file_path"
            :preview-src-list="[row.file_path]"
            fit="scale-down"
            style="height: 50px;"
          />
          <span v-else>{{ row.file_path }}</span>
        </template>
      </el-table-column>
      <el-table-column label="后缀名" width="220" align="center">
        <template slot-scope="{row}">
          <span>{{ row.file_suffix }}</span>
        </template>
      </el-table-column>

      <el-table-column label="文件类型" class-name="status-col" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ getFileType(row.file_type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="位置" class-name="status-col" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ saveHandler[row.save_handler] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button v-if="row.is_del==0" type="warning" size="mini" @click="handleRemove(row, $index)">移除</el-button>
          <el-button v-else-if="row.is_del==1" type="danger" size="mini" @click="handleDelete(row, $index)">彻底删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex flex-center">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>

    <!-- 创建 -->
    <el-dialog class="data-form-dialog" title="上传" :visible.sync="dialogFormVisible">
      <el-form label-position="right" label-width="120px">
        <el-upload
          ref="uploadForm"
          name="file"
          multiple
          :headers="headers"
          :action="action"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          :file-list="fileList"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        </el-upload>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchFileList,
  fetchRemoveFile,
  fetchDeleteFile
} from '@/api/attachment.js'
import {
  fetchUploadConfig
} from '@/api/upload.js'

import {
  getToken
} from '@/utils/auth.js'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
export default {
  name: 'AttachmentList',
  components: {
    Pagination
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      dialogFormVisible: false,
      submitLoading: false, // 提交中
      action: process.env.VUE_APP_BASE_API + '/uploader/file',
      headers: {
        Authorization: getToken()
      },
      statusType: {
        '0': 'danger',
        '1': 'danger',
        '10': 'success'
      },
      saveHandler: { aliyunOss: '阿里云OSS', localOss: '本地' },
      listQuery: {
        page: 1,
        sort_id: '-id',
        uid: '',
        isdel: 0,
        type: -1,
        limit: 10
      },
      delOptions: [{
        name: '正常',
        value: 0
      },
      {
        name: '回收站',
        value: 1
      }
      ],
      typeOptions: [{
        name: '全部类型',
        value: -1
      },
      {
        name: '图片',
        value: 0
      },
      {
        name: '视频',
        value: 1
      },
      {
        name: '音频',
        value: 2
      },
      {
        name: '头像',
        value: 5
      },
      {
        name: '其它',
        value: 127
      }
      ],
      fileList: []
    }
  },
  computed: {
    ...mapGetters(['uploadConfig', 'avatar', 'username'])
  },
  created() {
    this.getList()
    fetchUploadConfig().then(res => {
      this.$store.commit('settings/SET_UPLOADCONFIG', res.data)
    })
  },
  methods: {
    handleUploadSuccess(res, file) {
      console.log(res)
      this.list.unshift({
        id: res.data.id,
        uid: res.data.uid,
        user: { id: res.data.uid, nickname: this.username },
        file_type: res.data.fileType,
        save_handler: res.data.saveHandler,
        file_path: res.data.url,
        file_name: res.data.fileName,
        file_suffix: res.data.fileExt,
        is_del: 0
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 上传
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    beforeUpload(file) {
      console.log(file)
      const type = this.$U.getFileExtName(file.name)
      const size = file.size / 1024 / 1024
      const i = this.uploadConfig.uploadFileExt.findIndex(v => v == type)
      if (i === -1) {
        this.$message.error('上传文件不能是' + type.toUpperCase() + '格式!')
        return false
      }console.log(size)
      if (size > this.uploadConfig.uploadFileMaxSize) {
        this.$message.error('上传文件大小不能超过 ' + this.uploadConfig.uploadFileMaxSize + 'MB!')
        return false
      }
    },
    handleDelete(row, index) {
      this.$confirm('确定要彻底删除吗？删除后不可恢复！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'

            fetchDeleteFile(row.id).then((res) => {
              this.$notify({
                title: '提示',
                message: '已删除',
                type: 'success',
                duration: 3000
              })
              this.list.splice(index, 1)

              instance.confirmButtonLoading = false
              done()
            }, (err) => {
              this.$notify({
                title: '提示',
                message: err.message || '删除失败',
                type: 'error',
                duration: 3000
              })
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            done()
          }
        }
      })
    },
    handleRemove(row, index) {
      this.$confirm('确定要移除到回收站吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'

            fetchRemoveFile(row.id).then((res) => {
              this.$notify({
                title: '提示',
                message: '已移除到回收站',
                type: 'success',
                duration: 3000
              })
              this.list.splice(index, 1)

              instance.confirmButtonLoading = false
              done()
            }, (err) => {
              this.$notify({
                title: '提示',
                message: err.message || '移除失败',
                type: 'error',
                duration: 3000
              })
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            done()
          }
        }
      })
    },
    submitUpload() {
      this.$refs.uploadForm.submit()
    },
    getAvatarImage(url) {
      return this.$utils.getAvatarImage(url)
    },
    getFileType(e) {
      const i = this.typeOptions.findIndex(v => v.value == e)
      console.log(this.typeOptions[i])
      if (i > -1) return this.typeOptions[i].name
      return ''
    },
    getSaveType(e) {

    },
    getList() {
      fetchFileList(this.listQuery).then(res => {
        this.listLoading = false
        this.list = res.data.items
        this.total = res.data.total
      }, rej => {
        this.listLoading = false
      })
    },
    // 排序更新
    sortChange(data) {
      const {
        prop,
        order
      } = data
      if (prop === 'id') {
        this.sortByID(order)
      } else if (prop === 'sort') {
        this.sortBySort(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort_id = '+id'
      } else {
        this.listQuery.sort_id = '-id'
      }
      this.getList()
    },
    sortBySort(order) {
      if (order === 'ascending') {
        this.listQuery.sort_id = '+sort'
      } else {
        this.listQuery.sort_id = '-sort'
      }
      this.getList()
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort_id
      if (sort === `+${key}`) {
        return 'ascending'
      } else if (sort === `-${key}`) {
        return 'descending'
      }
    },
    jump(url) {
      this.$router.push(url)
    }
  }
}
</script>

<style>
  .el-dialog {
    width: 550px;
  }

  .cate-icon {
    width: 2.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
